package com.ddlaw.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ddlaw.constant.Constant;
import com.ddlaw.entity.TLawQuestionCustom;
import com.ddlaw.entity.TLawQuestions;
import com.ddlaw.entity.TLawReplyCustom;
import com.ddlaw.entity.TLawyer;
import com.ddlaw.entity.TUsers;
import com.ddlaw.service.LawQuestionService;
import com.ddlaw.service.LawyerDetailService;
import com.ddlaw.service.UserService;
import com.ddlaw.util.CookieTool;
import com.ddlaw.util.MsgCode;
import com.ddlaw.util.MsgSend;
import com.ddlaw.util.SecretUtil;
import com.ddlaw.util.XssFilter;
/**
 * 用户控制器
 * @author YunLong
 *
 */
@Controller
@RequestMapping(value="/user")
public class UserController extends BaseController{
		
		@Resource
		UserService userService;
		@Resource
		LawQuestionService questionService;
		@Resource
		LawyerDetailService detailService;
		
		
		
		/**
		 * 注册页面
		 * @return 注册页面
		 */
		@RequestMapping(value="register",method=RequestMethod.GET)
		public String register(){
			return "user/register";
		}
		
		/**
		 * 用户注册
		 * @param user		用户信息
		 * @param yzm		验证码
		 * @return				添加用户到数据库
		 */
		@RequestMapping(value="register",method=RequestMethod.POST)
		@ResponseBody
		public Map<String,Object> register(TUsers user,@RequestParam("yzm") String yzm){
			Map<String,Object> result = new HashMap<String,Object>();
			if("".equals(user.getUsername()) || "".equals(user.getPassword())){
				result.put("ERROR_CODE", "003");
				result.put("MSG", "请输入用户名或密码！");
				return result;
			}
			HttpSession session = getHttpSession();
			//最终校验手机号是否注册，若已经注册提示错误(防止重复注册)
			if(userService.getUserByName(user.getUsername())!= null){
				result.put("ERROR_CODE", "003");
				result.put("MSG", "该账号已经注册！");
				return result;
			}
		
				String validateCode = (String)session.getAttribute(user.getUsername());
				if(yzm != null && yzm.equals(validateCode)){
					userService.addUser(user);
					session.removeAttribute(user.getUsername());
					session.setAttribute("user", user);
					result.put("SUCCESS_CODE", "200");
					return result;
				}else{
					result.put("ERROR_CODE", "004");
					result.put("MSG", "验证码不正确！");
					return result;
				}
		}
		
		/**
		 * 检验用户是否注册
		 * @param tel
		 * 					 手机号
		 * @return STATE = 1：用户未注册;STATE = 2：用户已经注册
		 */
		@RequestMapping("isMobileEngaged")
		@ResponseBody
		public Map<String,Object> validateUser(@RequestParam("tel") String tel) throws Exception{
			Map<String,Object> result = new HashMap<String,Object>();
			if(tel == null || "".equals(tel)){
				result.put("MSG", "请输入账号!");
				return result;
			}
			TUsers user = userService.getUserByName(tel);
			if(user == null){
				//用户未注册,状态为1
				result.put("STATE", "1");
				result.put("STATUS", 1);
				result.put("MSG", "该用户尚未注册!");
			}else{
				//用户已经注册,状态为2
				result.put("STATE", "2");
				result.put("STATUS", 2);
				result.put("MSG", "该用户已经注册!");
			}
			return result;
		}
		
		/**
		 * 获取手机验证码
		 * @param tel
		 * 					手机号
		 * @return
		 */
		@RequestMapping(value="/code",method=RequestMethod.GET)
		@ResponseBody
		public Map<String,Object> getCode(@RequestParam("tel") String tel,Integer status){
			Map<String,Object> result = new HashMap<String,Object>();
			if(status == null){
				result.put("ERROE_CODE", "009");
				result.put("MSG", "系统异常，请稍后再试！");
				return result;
			}
			String msgId = Constant.REGISTER_ID;
			if(status == 2){
				msgId = Constant.FORGET_ID;
			}
			boolean flag = true;
			Date oldTime = (Date) getHttpSession().getAttribute("CodeDate");
			//若为空表示首次获取验证码,不是恶意操作
			if (oldTime != null){
				Date now = new Date();
				//若点击获取验证码前后小于一分钟则为恶意操作拒绝获取。
				if (now.getTime() - oldTime.getTime() < 60 * 1000) {
					flag = false;
				}
			}
			
			if(flag){
				//产生6位手机验证码
				String validateCode = MsgCode.getValidateCode();
				System.out.println("TelCode:" + validateCode);
				String msg[] = new String[]{validateCode,"3"};
				//msgId表示短信模板号,msg为短信内容
				if(!"".equals(tel) && tel != null &&  MsgSend.SMS(tel, msgId, msg) == 1){
					// 将验证码存入session中，手机号作为唯一的key值
					HttpSession codeSession=getHttpSession();
					codeSession.setAttribute(tel, validateCode);
					//设置session有效时间为3分钟
					codeSession.setMaxInactiveInterval(60*3);
					//设置验证码获取时间为新的时间
					getHttpSession().setAttribute("CodeDate", new Date());
				}else{
					//手机号为空或获取短信失败
					result.put("ERROR_CODE", "005");
					result.put("MSG", "获取验证码失败！");
					return result;
				}
			}
			return result;
		}
		
		/***
		 * 咨询问题
		 * @param questions
		 * @return
		 */
		@RequestMapping(value="ask",method=RequestMethod.POST)
		@ResponseBody
		public Map<String,Object> ask(TLawQuestions questions){
			Map<String,Object> result = new HashMap<String, Object>();
			TUsers user= (TUsers) getHttpSession().getAttribute("user");
			if(user == null){
				result.put("MSG", "请先登录！");
				result.put("ERROR_CODE", 100);
				return result;
			}
			String title = questions.getQuestitle();
			String content = questions.getQuescontent();
			if("".equals(title) || "".equals(content) || title==null || content == null){
				result.put("MSG", "请完善信息后提交！");
				result.put("ERROR_CODE", 100);
				return result;
			}
			Map<String,Object> params = new HashMap<String,Object>();
			params.put("lawyerId", questions.getAnswererid());
			List<TLawyer> lawyer = detailService.getLawyer(params);
			if(lawyer.size()==0 || lawyer.get(0).getState() == 1){
				result.put("MSG", "系统繁忙！请稍后再试！");
				result.put("ERROR_CODE", 100);
				return result;
			}
			questions.setQuestitle(XssFilter.cleanXSS(title));
			questions.setQuescontent(XssFilter.cleanXSS(content));
			questions.setQuizzerid(user.getUserid());
			questionService.addQuestion(questions);
			result.put("MSG", "问题提交成功,请等待回复！");
			result.put("SUCCESS_CODE", 200);
			return  result;
		}
		
		@RequestMapping(value="login",method=RequestMethod.GET)
		public String loginView(){
			return "user/login";
		}
		
		/**
		 * 登录
		 * @param username
		 * 						用户名
		 * @param password
		 * 						密码
		 * @return
		 */
		@RequestMapping(value="/login",method=RequestMethod.POST)
		@ResponseBody
		public Map<String,Object> login(@RequestParam("username")String username, 
												@RequestParam("password") String password,
												HttpServletResponse response) throws Exception{
			Map<String,Object> result = new HashMap<String,Object>();
			if(username == null || "".equals(username)){
				result.put("ERROR_CODE", "001");
				result.put("MSG", "请输入用户名！");
				return result;
			}
			  TUsers user = userService.login(username, password);
				if(user != null){
						CookieTool.addCookie(response, "username",SecretUtil.encodeBase64(user.getUsername()), Constant.COOKIE_TIME);
						getHttpSession().setAttribute("user", user);
						result.put("SUCCESS_CODE", "200");
						result.put("STATE", 0);
						return result;
				}else{
						result.put("ERROR_CODE", "002");
						result.put("MSG", "用户名与密码不匹配！");
						return result;
				}
			}
		
			/**
			 * 普通用户个人中心
			 * @param model		数据模型
			 * @return
			 */
			@RequestMapping(value="/person",method=RequestMethod.GET)
			public String person(Model model){
				Map<String,Object> params = new HashMap<String, Object>();
				TUsers user = (TUsers) getHttpSession().getAttribute("user");
				params.put("state",0);
				params.put("userId", user.getUserid());
				List<TLawQuestionCustom> questions  = questionService.getUserQues(params);
				params.put("state",1);
				List<TLawReplyCustom> replys  = questionService.getLawyerAns(params);
				model.addAttribute("questions", questions);
				model.addAttribute("replys", replys);
				return "user/personal";
			}
			
			/**
			 * 用户退出登陆
			 * @return		返回首页
			 */
			@RequestMapping(value="logout")
			public String logout(){
				TUsers users = (TUsers) getHttpSession().getAttribute("user");
				if(users != null){
					getHttpSession().removeAttribute("user");
				}
				return "redirect:/index/home";
			}
	}
